using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Mvc;
using System.Security.Claims;
using TagDemo.Api.Models;

namespace TagDemo.Api.Controllers
{
    public class AccountController : Controller  // 修改为继承 Controller
    {
        [HttpGet]  // 修改路由特性
        public IActionResult Login(string? returnUrl = null)
        {
            ViewBag.ReturnUrl = returnUrl;
            return View();
        }

        [HttpPost]  // 修改路由特性
        public async Task<IActionResult> Login(LoginModel model, string? returnUrl = null)
        {
            if (model.Username == "admin" && model.Password == "123456")
            {
                var claims = new List<Claim>
                {
                    new Claim(ClaimTypes.Name, model.Username),
                    new Claim(ClaimTypes.Role, "Admin")
                };

                var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
                var principal = new ClaimsPrincipal(identity);

                await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal);

                if (!string.IsNullOrEmpty(returnUrl))
                {
                    return Redirect(returnUrl);
                }
                return RedirectToAction("Index", "Tag");
            }

            ModelState.AddModelError("", "Invalid login attempt");
            return View(model);
        }

        [Route("api/auth/token")]  // 保留 API 路由
        [HttpPost]
        public async Task<IActionResult> GetToken([FromBody] LoginModel model)
        {
            if (model.Username == "admin" && model.Password == "123456")
            {
                var claims = new List<Claim>
                {
                    new Claim(ClaimTypes.Name, model.Username),
                    new Claim(ClaimTypes.Role, "Admin")
                };

                var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
                var principal = new ClaimsPrincipal(identity);

                await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal);

                return Ok(new { token = "demo_token" });
            }

            return Unauthorized();
        }
    }
}